import requests

# Odoo 服务器信息
odoo_url = 'http://127.0.0.1:8081'   # 本地测试地址
db = 'odoo17e'                      # 本地测试数据库名称
username = 'admin'                   # odoo 管理员用户
password = '123456'                  # 管理员密码

# 获取访问令牌信息
def odoo_login():
    login_url = f'{odoo_url}/web/session/authenticate'
    payload = {
        'jsonrpc': '2.0',
        'params': {
            'db': db,
            'login': username,
            'password': password,
        }
    }
    # 发送POST请求以进行身份验证
    response = requests.post(login_url, json=payload)

    # 检查响应状态
    if response.status_code == 200:
        # 获取请求头信息
        response_headers = response.headers
        headers = response_headers.get('Set-Cookie')
        # 获取请求体信息
        response_body = response.json()
        uid = response_body['result']['uid']
        # 返回请求头和请求体
        return {
            "headers": headers,
            "uid": uid,
        }
    else:
        print("Login failed!")

# 测试访问odoo
def get_partners_info():
    session_info = odoo_login()
    headers_ = session_info.get('headers')
    uid = session_info.get('uid')

    print(headers_)
    print(uid)
    # 访问令牌
    headers = {
        'Content-Type': 'application/json',
        'X-Openerp-Session-Id':headers_,
    }

    # 调用 Odoo 的 search_read 方法以获取数据
    search_url = f'{odoo_url}/jsonrpc'
    search_payload = {
        'jsonrpc': '2.0',
        'method': 'call',
        'args': [
            db,
            uid,
            password,
            'res.partner',  # 访问的 模型
            'search_read',  # 搜索
            [],  # 搜索条件，这里为空表示获取所有记录
            {'fields': ['id', 'name', 'email'], 'limit': 10}  # 指定需要返回的字段和限制记录数
        ],
        'id': 1,
    }

    response = requests.post(search_url, headers=headers, json=search_payload)
    return response.json()


if __name__ == '__main__':
    partners_data = get_partners_info()

